import {get,set } from 'lodash';
const removeDetailRow = (records, index, recordDeleteRow) => {
    const newRecords = [];
    if (index === -1) {
        newRecords.push({ detail_index: 1 });
    }
    let detailIndex = 1;
    records.forEach((record, recordIndex) => {
        if (recordIndex < index) {
            newRecords.push({ ...record, detail_index: detailIndex++ });
        } else if (recordIndex > index) {
            newRecords.push({ ...record, detail_index: detailIndex++ });
        } else {
            if (record.id) {
                recordDeleteRow(record.id);
            }
        }
    });
    return newRecords;
}
export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        context.suspendPaint();
        try {
            const { table, store, row: currentRow, sheetName,oldDelete ,deleteRowCount} = options;
            const bindingPath = table.bindingPath();
            if (isUndo) {
                store.dataSourceInstance.setValue(bindingPath, options.oldValue);
            } else {
                const records = options.oldValue = store.dataSourceInstance.getValue(bindingPath);
                const { row } = table.dataRange();
                for(var i=deleteRowCount; i>0; i--){
                    const records = store.dataSourceInstance.getValue(bindingPath);
                    const newRecords = removeDetailRow(records, row > currentRow ? -1 : currentRow - row + i-1, (deleteId) => {
                        const deletedRows = get(store.deletedRows, bindingPath);
                        if (deletedRows) {
                            deletedRows.push(deleteId);
                        } else {
                            set(store.deletedRows, bindingPath, [deleteId]);
                        }
                    });
                    store.dataSourceInstance.setValue(bindingPath, newRecords);
                }
            }
            table.bindingPath(bindingPath);
            store.calcAll(true, sheetName);
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        }
        context.resumePaint();
    }
};